import threading
import time
import can

class Precondition:
    def __init__(self, can_bus):
        self.can_bus = can_bus
        self.running = False
        self.thread = None

    def start(self):
        if not self.running:
            self.running = True
            self.thread = threading.Thread(target=self._send_messages)
            self.thread.start()

    def stop(self):
        if self.running:
            self.running = False
            if self.thread:
                self.thread.join()
                self.thread = None

    def _send_messages(self):
        while self.running:
            # 在这里定义要发送的CAN报文
            message = can.Message(arbitration_id=0x123, data=[0, 1, 2, 3, 4, 5, 6, 7], is_extended_id=False)
            try:
                self.can_bus.send(message)
                time.sleep(0.1)  # 每100ms发送一次,可根据需要调整
            except can.CanError:
                print("发送CAN报文失败")

    def __del__(self):
        self.stop()
